from lib import *
from cluster1d import *
from pprint import pprint

def data(x) : return '../../trunk/data/' + x + '.csv'

class Table:
  def __init__(self,file) :
    self.data=[]
    for n,row in rows(file,-1):
      self.header(row) if n==0 else self.cells(row)
    self.complete()
  def complete(self):
    self.discretizeColumns()
  def header(self,names) :
    self.names = names
    self.nums=[]; self.syms=[];
    for i,head in enumerate(names):
      self.klass=i
      (self.nums if "$" in head else self.syms).append(i)
  def cells(self,cells) :
    for col in self.nums: 
      if cells[col] != '?':
        cells[col] = float(cells[col])
    self.data.append(cells)   
  def discretizeColumns(self):
    cols= zip(*self.data)
    for col in self.nums:
      if col != self.klass:
        cols[col] = self.discreteColumn(cols[col])
    self.data = zip(*cols)
  def discreteColumn(self,nums):
    ranks = divlist(nums,cohen=0.2,minObs=4,accept=lambda x: x != "?")
    return [self.discreteNumber(x,ranks) for x in nums] 
  def discreteNumber(self,x,ranks) :
    return x if x == "?" else ranks[x].rank

@demo
def tabled1(): 
  pprint(Table(data("weathern")).data)

@demo
def tabled2(): 
  pprint(Table(data("coc81")).data)

@demo
def tabled3(): 
  Table(data("autompg25K"))

@demo
def tabled4(): 
  pprint(Table(data("desharnais")).data)


